<script setup>
  import {ref} from "vue"
  import { captchaCheck } from "@/api/verify"
  import { useRouter } from "vue-router"

  // 路由实例对象
  const router = useRouter()
  // 验证码信息
  const verifyCode = ref("")
  // 请求地址
  const verifyImgURL = ref("https://127.0.0.1:8443/home/captcha")
  // 更换验证图片
  const onChange = () => {
    verifyImgURL.value = "https://127.0.0.1:8443/home/captcha?dt=" + Date.now()
  }
  // 提交验证码进行验证
  const onConfirm = async () => {
    // 非空校验
    if(!verifyCode.value) {
      return alert("验证码不能为空！")
    }
    // 发送请求，接收校验结果
    const result = await captchaCheck(verifyCode.value)
    if(result.data) {
      // 校验成功，跳转页面
      router.push("success")
    } else {
      // 校验失败，提示+置空输入
      alert("验证码错误或失效，请重新获取验证码进行验证")
      verifyCode.value = ""
    }
    
  }
</script>

<template>
  <div class="containner">
    <table>
      <tr>
        <td>
          <span>验证码：</span>
          <input type="text" 
          placeholder="请输入验证码"
          v-model="verifyCode">
        </td>
        <td>
          <img :src="verifyImgURL" 
          height="32px" width="100px" 
          title="看不清，换一张"
          @click="onChange">
        </td>
      </tr>
    </table>
    <div class="btn-box">
        <button class="btn"
        @click="verifyCode = ''">重置</button>
        <button class="btn confirm"
        @click="onConfirm">确认</button>
      </div>
  </div>
</template>

<style scoped>
  .containner {
    display: flex;
    justify-content: center;
    flex-direction: column;
    margin: 100px auto;
    width: 420px;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 1em;
  }
  .btn-box {
    width: 100%;
    display: flex;
    justify-content: space-around;
    margin-top: 20px;
  }
  .btn {
    width: 120px;
    height: 32px;
    border: none;
    border-radius: 2em;
    cursor: pointer;
  }
  .confirm {
    background-color: rgb(21, 172, 139);
    color: white;
  }
  td {
    padding: 0 0.5em;
  }
  input {
    height: 27px;
    border: 1px solid #ccc;
    outline: none;
  }
</style>